﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Collections.ObjectModel;
using System.Data.SqlClient;
using TracNghiemTinHocDaiCuong.Common;
using TracNghiemTinHocDaiCuong.ThucThe;

namespace TracNghiemTinHocDaiCuong.DAO
{
    public class DiemDAO
    {
        public static Diem DoiTuong(IDataRecord read)
        {
            return new Diem
            {
                MaDiem = Methods.ConvertNumber(read["MaDiem"].ToString()),
                MaND = Methods.ConvertNumber(read["MaND"].ToString()),
                MaDT = Methods.ConvertNumber(read["MaDT"].ToString()),
                DiemBaiThi = Methods.ConvertFloating(read["Diem"].ToString()),
                NgayThi = Methods.ConvertDateTime(read["NgayThi"].ToString())
            };
        }

        public static IList<Diem> LayDanhSach()
        {
            IList<Diem> danhSach = new List<Diem>();
            string query = string.Format("SELECT * FROM Diem");
            IDataReader read = SqlHelper.ExecuteReader(query);
            while(read.Read())
            {
                danhSach.Add(DoiTuong(read));
            }
            return danhSach;
        }

        public static bool Them(Diem diem)
        {
            string query = string.Format("INSERT INTO Diem(MaND, MaDT, Diem, NgayThi) VALUES(@MaND, " +
            "@MaDT, @Diem, @NgayThi)");
            var parameter = new Collection<SqlParameter>
            {
                new SqlParameter("@MaND", diem.MaND),
                new SqlParameter("@MaDT", diem.MaDT),
                new SqlParameter("@Diem", diem.DiemBaiThi),
                new SqlParameter("@NgayThi", diem.NgayThi)
            };
            SqlHelper.ExecuteNonQuery(query, parameter);
            return true;
        }

        public static bool Sua(Diem diem)
        {
            string query = string.Format("UPDATE Diem SET MaND=@MaND, MaDT=@MaDT, Diem=@Diem, NgayThi=@NgayThi " +
            "WHERE MaDiem=@MaDiem");
            var parameter = new Collection<SqlParameter>
            {
                new SqlParameter("@MaDiem", diem.MaDiem),
                new SqlParameter("@MaND", diem.MaND),
                new SqlParameter("@MaDT", diem.MaDT),
                new SqlParameter("@Diem", diem.DiemBaiThi),
                new SqlParameter("@NgayThi", diem.NgayThi)
            };
            SqlHelper.ExecuteNonQuery(query, parameter);
            return true;
        }

        public static bool Xoa(Diem diem)
        {
            string query = string.Format("DELETE FROM Diem WHERE MaDiem=@MaDiem");
            var parameter = new Collection<SqlParameter>
            {
                new SqlParameter("@MaDiem", diem.MaDiem)
            };
            SqlHelper.ExecuteNonQuery(query, parameter);
            return true;
        }
    }
}